package cc.rengu.igas.mcps.core.service.trans.stagepay;

import cc.rengu.igas.channel.cups.facade.response.ConsumeResponse;
import cc.rengu.igas.channel.upqc.facade.result.Result;
import cc.rengu.igas.mcps.common.constant.McpsParamConstant;
import cc.rengu.igas.mcps.common.constant.McpsTreeNodeConstant;
import cc.rengu.igas.mcps.common.enums.McpsAcctTypeEnum;
import cc.rengu.igas.mcps.common.enums.RespCodeEnum;
import cc.rengu.igas.mcps.core.realize.PosParamDealService;
import cc.rengu.igas.mcps.core.realize.impl.PosParamDealServiceImpl;
import cc.rengu.igas.mcps.core.service.base.RevsalService;
import cc.rengu.igas.mcps.facade.base.Header;
import cc.rengu.igas.mcps.facade.request.InstallmentCancelRevsalRequest;
import cc.rengu.igas.mcps.facade.response.InstallmentCancelRevsalResponse;
import cc.rengu.igas.share.common.constant.TransCacheConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.entity.MchntOrderInfo;
import cc.rengu.oltp.service.common.entity.PayOrderInfo;
import cc.rengu.oltp.service.common.entity.UserOrderInfo;
import cc.rengu.oltp.service.common.enums.BizStatusEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.OrderService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.service.realize.impl.OrderServiceImpl;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

public class InstallmentCancelRevsalService extends RevsalService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        InstallmentCancelRevsalRequest installmentCancelRevsalRequest = new InstallmentCancelRevsalRequest();
        ConvertUtil.convertOutput(installmentCancelRevsalRequest);
        return installmentCancelRevsalRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        BizResponse bizResponse = new BizResponse();
        InstallmentCancelRevsalRequest installmentCancelRevsalRequest = (InstallmentCancelRevsalRequest) request;
        InstallmentCancelRevsalResponse installmentCancelRevsalResponse = new InstallmentCancelRevsalResponse();
        ConvertUtil.convertOutput(installmentCancelRevsalResponse);
        //获取原商户订单
        MchntOrderInfo origMchntOrderInfo = (MchntOrderInfo) GlobalTransUtil.getCacheValue(TransCacheConstant.ORIG_MCHNT_ORDER_INFO);
        //获取原用户订单
        UserOrderInfo origUserOrderInfo = (UserOrderInfo) GlobalTransUtil.getCacheValue(TransCacheConstant.ORIG_USER_ORDER_INFO);

        PosParamDealService posParamDealService = new PosParamDealServiceImpl();
        //获取原通道支付订单
        PayOrderInfo oriPayOrderInfoESB = (PayOrderInfo) GlobalTransUtil.getCacheValue(TransCacheConstant.ORIG_PAY_ORDER_INFO);

        //调用esb银数冲正接口
        if (!McpsAcctTypeEnum.OWN_CREDIT.getAcctType().equals(oriPayOrderInfoESB.getPayerAcctType())) {
            rglog.error("只允许本行贷记卡分期消费!! acctType:{}", oriPayOrderInfoESB.getPayerAcctType());
            throw new BizException(RespCodeEnum.ACCT_TYPE_NOT_SUPPORT.getRespCode(), RespCodeEnum.ACCT_TYPE_NOT_SUPPORT.getRespDesc());
        }
        updcRevsal(oriPayOrderInfoESB, origMchntOrderInfo, origUserOrderInfo, installmentCancelRevsalRequest, bizResponse, posParamDealService);

        /* 重组响应结果 */
        Header header = new Header();
        BeanUtil.beanCopy(installmentCancelRevsalRequest.getHeader(), header);
        installmentCancelRevsalResponse.setHeader(header);
//        installmentCancelRevsalResponse.setReferenceNo();
        bizResponse.setRspSysId(AppParamConstant.IGAS);
        bizResponse.setResult(installmentCancelRevsalResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        InstallmentCancelRevsalResponse installmentCancelRevsalResponse = (InstallmentCancelRevsalResponse) bizResponse.getResult();
        installmentCancelRevsalResponse.setRespCode(bizResponse.getRespCode());
        installmentCancelRevsalResponse.setRespDesc(bizResponse.getRespDesc());
        ConvertUtil.convertInput(installmentCancelRevsalResponse);
    }

    /*
     *调用冲正
     */
    private void updcRevsal(PayOrderInfo oriPayOrderInfoESB, MchntOrderInfo origMchntOrderInfo,
                            UserOrderInfo origUserOrderInfo, InstallmentCancelRevsalRequest installmentCancelRevsalRequest,
                            BizResponse bizResponse, PosParamDealService posParamDealService) throws Exception {
        DubboService dubboService = new DubboServiceImpl();
        OrderService orderService = new OrderServiceImpl();
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String instId = xmlTreeUtil.getXmlTreeStringValue(McpsTreeNodeConstant.INST_ID);
        String sysNum = xmlTreeUtil.getXmlTreeStringValue(McpsTreeNodeConstant.SYS_SEQ_NUM);
        /*准备请求报文*/
        /* TODO 调用服务*/
        Result<ConsumeResponse> result = new Result<>();
        ConsumeResponse consumeResponse = new ConsumeResponse();
        consumeResponse.setRespCode(McpsParamConstant.DUBBO_SUCCESS);
        consumeResponse.setRespDesc("交易成功");
        consumeResponse.setSettleDate(DateUtil.getCurrentDate());
        result.setResult(consumeResponse);
        result.setSuccess(true);
        rglog.debug("dubbo调用CUPS消费结果：{}", JSON.toJSONString(result));
        /*冲正失败处理*/
        if (null == result || null == result.getResult()
                || (!McpsParamConstant.DUBBO_SUCCESS.equals(result.getResult().getRespCode())
                && !McpsParamConstant.DUBBO_OVERTIME.equals(result.getResult().getRespCode())
                && !McpsParamConstant.COMMUNICATION_OVERTIME.equals(result.getResult().getRespCode()))) {
            bizResponse.setRespCode(RespCodeEnum.TRANS_FAIL.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.TRANS_FAIL.getRespDesc());
        } else if (result.isSuccess() && McpsParamConstant.DUBBO_SUCCESS.equals(result.getResult().getRespCode())) {
            List<MchntOrderInfo> oriMchntOrderInfoList = new ArrayList<>();
            //更新原支付订单表已冲正
            oriPayOrderInfoESB.setBizStatus(BizStatusEnum.REVSAL.getStatus());
            //更新原商户订单表已冲正
            origMchntOrderInfo.setBizStatus(BizStatusEnum.REVSAL.getStatus());
            oriMchntOrderInfoList.add(origMchntOrderInfo);
            //更新原用户订单表已冲正
            origUserOrderInfo.setBizStatus(BizStatusEnum.REVSAL.getStatus());
            orderService.updateOrderInfo(origUserOrderInfo, oriMchntOrderInfoList, oriPayOrderInfoESB);
            bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        } else {
            bizResponse.setRespCode(RespCodeEnum.POS_RSP_TIME_OUT.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.POS_RSP_TIME_OUT.getRespCode());
        }
    }
}
